package com.example.demo.test.lecture.algorithm;

import java.util.HashMap;

public class SumOfNums {
    public static int[] twoSum(int[] nums, int target) {
        int[] returnBums = new int[2];
        int length = nums.length;
        for (int i = 0; i < length - 1; i++) {
            for (int j = i + 1; j < length; j++) {
                System.out.println("i: " + i + ", j:" + j);
                if (nums[i] + nums[j] == target) {
                    returnBums[0] = i;
                    returnBums[1] = j;
                    return returnBums;
                }
            }
        }
        return null;
    }

    public static int[] twoSum1(int[] nums, int target) {
        int[] reNum = new int[2];
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0, length = nums.length; i < length; i++) {
            if (map.containsKey(nums[i])) {
                reNum[0] = i;
                reNum[1] = map.get(nums[i]);
            }
            map.put(target - nums[i], i);
        }
        return reNum;
    }

    public static void main(String[] args) {
        int[] nums = {3, 2, 4};
        int[] num = twoSum1(nums, 6);
        for (int i = 0; i < num.length; i++) {
            System.out.println(num[i]);
        }
        ListNode l1 = new ListNode(2);
        ListNode l3 = new ListNode(4);
        ListNode l4 = new ListNode(4);
        l1.next = l3;
        l3.next = l4;

        ListNode l2 = new ListNode(2);
        ListNode l5 = new ListNode(8);
        ListNode l6 = new ListNode(4);
        l2.next = l5;
        l5.next = l6;
        System.out.println(addTwoNumbers(l1, l2).toString());

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode root = new ListNode(0);
        ListNode cusor = root;
        int carry = 0;
        while(l1!=null || l2!=null || carry != 0){
            int l1Val = l1 != null ? l1.val : 0;
            int l2Val = l2 != null ? l2.val : 0;
            int sumVal = l1Val + l2Val + carry;
            carry = sumVal / 10;

            ListNode sumNode = new ListNode(sumVal % 10);
            cusor.next = sumNode;
            cusor = sumNode;


            if(l1 != null)l1 = l1.next;
            if(l2 != null)l2 = l2.next;
        }
        return root.next;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
    public String toString(){
        String appendedString = val + "";
        while(next != null) {
            appendedString += " " + next.val;
            next = next.next;
        }
        return "[" + appendedString + "]";
    }
}
